const db = require('../tool/db.js');

async function add(data) {
    if (!data.content) {
        return { code: 0, msg: '评价内容不能为空', data: '' }
    }
    if (!data.star) {
        return { code: 0, msg: '评价星级不能为空', data: '' }
    }
    let sql = `insert into judge (uid,content,star,gid,o_gid,photo,judgetime) values(?,?,?,?,?,?,?)`
    let [result] = await db.query(sql, [data.uid, data.content, data.star, data.gid, data.o_gid, data.photo, data.judgetime]);
    if (result.insertId) {
        await db.query(`update order_goods set isjudged=1 where id=${data.o_gid} and gid=${data.gid}`)
        return { code: 1, msg: '完成本次评价', data: result.insertId }
    } else {
        return { code: 0, msg: '评价失败', data: '' }
    }
}

async function list(options) {
    if (options.gid) {
        let sql = `select judge.* ,user.username,user.userImg from judge left join user on judge.uid
        = user.id  where gid=${options.gid}`;
        let [lists] = await db.query(sql);
        // 查询符合条件的总数量
        let [[{ total }]] = await db.query(`SELECT COUNT(*) as total FROM judge left join user on judge.uid
        = user.id  where gid=${options.gid}`)
        return { lists, total }
    }else {
        let sql = `select judge.* ,order_goods.gname,order_goods.gphoto,order_goods.gprice,order_goods.gcount from judge  join order_goods on judge.o_gid
        = order_goods.id  where uid=${options.uid} and isshow=1`;
        let [lists] = await db.query(sql);
        // 查询符合条件的总数量
        let [[{ total }]] = await db.query(`SELECT COUNT(*) as total FROM judge  join order_goods on judge.o_gid
        = order_goods.id  where uid=${options.uid} and isshow=1`)
        return { lists, total }
    }
    
}

async function del(data){
    let sql=`update judge set isshow=0 where id=${data.id} and uid=${data.uid}`
    let [res]=await db.query(sql)
    if (res.affectedRows){
        return {code:1, msg:'操作成功', data:''}
    }else{
        return {code:0, msg:'操作失败，请重试', data:''}
    }
}



module.exports = { add, list ,del}